<template>
  <div>
    <a-page-header :ghost="false" title="站点配置">
      <div class="ele-text-secondary"> 用于配置站点的基本信息 </div>
    </a-page-header>
    <div class="ele-body">
      <a-card :bordered="false">
        <a-form
          ref="formRef"
          :model="form"
          :rules="rules"
          :label-col="styleResponsive ? { sm: 4, xs: 24 } : { flex: '100px' }"
          :wrapper-col="styleResponsive ? { sm: 20, xs: 24 } : { flex: '1' }"
          style="max-width: 800px; margin: 0 auto"
        >
          <a-form-item label="站点域名" name="url">
            <a-input v-model:value="form.url">
              <template #addonBefore>
                <a-select v-model:value="form.urlPre" style="width: 90px">
                  <a-select-option value="http://">http://</a-select-option>
                  <a-select-option value="https://">https://</a-select-option>
                </a-select>
              </template>
            </a-input>
          </a-form-item>
          <a-form-item label="站点名称" name="siteName">
            <a-input
              allow-clear
              placeholder="请输入站点名称"
              v-model:value="form.siteName"
            />
          </a-form-item>
          <a-row :gutter="16">
            <a-col
              v-bind="
                styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 12 }
              "
            >
              <a-form-item
                label="站点icon"
                name="icon"
                :label-col="
                  styleResponsive ? { md: 8, sm: 4, xs: 24 } : { flex: '90px' }
                "
                :wrapper-col="
                  styleResponsive ? { md: 21, sm: 20, xs: 24 } : { flex: '1' }
                "
              >
                <ele-image-upload
                  v-model:value="icon"
                  :limit="1"
                  :before-upload="onBeforeUpload"
                  :remove-handler="iconRemoveHandler"
                  :item-style="{ width: '150px', height: '100px' }"
                  :button-style="{ width: '150px', height: '100px' }"
                  @upload="iconUpload"
                />

              </a-form-item>
            </a-col>
            <a-col
              v-bind="
                styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 12 }
              "
            >
              <a-form-item
                label="站点logo"
                name="logo"
                :label-col="
                  styleResponsive ? { md: 8, sm: 4, xs: 24 } : { flex: '90px' }
                "
                :wrapper-col="
                  styleResponsive ? { md: 21, sm: 20, xs: 24 } : { flex: '1' }
                "
              >
                <ele-image-upload
                  v-model:value="logo"
                  :limit="1"
                  :before-upload="onBeforeUpload"
                  :remove-handler="logoRemoveHandler"
                  :item-style="{ width: '150px', height: '100px' }"
                  :button-style="{ width: '150px', height: '100px' }"
                  @upload="logoUpload"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="关键字">
            <a-input
              allow-clear
              placeholder="请输入关键字"
              v-model:value="form.keywords"
            />
          </a-form-item>
          <a-form-item label="站点描述">
            <a-textarea
              :rows="4"
              v-model:value="form.description"
              placeholder="请输入站点描述"
            />
          </a-form-item>
          <a-form-item label="ICP备案">
            <a-input
              allow-clear
              placeholder="请输入ICP备案"
              v-model:value="form.icp"
            />
          </a-form-item>
          <a-form-item label="公安备案">
            <a-input
              allow-clear
              placeholder="请输入公安备案"
              v-model:value="form.beian"
            />
          </a-form-item>
          <a-form-item label="存储目录">
            <a-input
              allow-clear
              placeholder="请输入存储目录"
              v-model:value="form.storagePath"
            />
          </a-form-item>
          <a-form-item label="存储位置">
            <a-radio-group v-model:value="form.storage">
              <a-radio value="local">本地</a-radio>
              <a-radio value="qiniu">七牛云</a-radio>
              <a-radio value="cos">腾讯云</a-radio>
            </a-radio-group>
          </a-form-item>
          <a-form-item
            :wrapper-col="
              styleResponsive ? { sm: { offset: 4 } } : { offset: 3 }
            "
          >
            <a-space size="middle">
              <a-button @click="finishPageTab()">关闭</a-button>
              <a-button type="primary" :loading="loading" @click="submit">
                提交
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive } from 'vue';
  import { message } from 'ant-design-vue/es';
  import type { FormInstance, Rule } from 'ant-design-vue/es/form';
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import useFormData from '@/utils/use-form-data';
  import { finishPageTab } from '@/utils/page-tab-util';
  import { SiteForm } from '@/api/setting/model';
  import {
    BeforeUploadType,
    ItemType
  } from 'ele-admin-pro/es/ele-image-upload/types';
  import request from '@/utils/request';
  import { submitForm, getConfig } from '@/api/setting';
  import { assignObject } from 'ele-admin-pro';

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    url: [
      {
        required: true,
        message: '请输入url',
        type: 'string',
        trigger: 'blur'
      }
    ],
    siteName: [
      {
        required: true,
        type: 'string',
        message: '请输入站点名',
        trigger: 'blur'
      }
    ]
  });
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  //
  const formRef = ref<FormInstance | null>(null);

  // 加载状态
  const loading = ref(false);
  const icon = ref<any>([]);
  const logo = ref<any>([]);
  // 表单数据
  const { form, resetFields } = useFormData<SiteForm>({
    type: 'site',
    urlPre: 'http://',
    url: undefined,
    icon: undefined,
    logo: undefined,
    siteName: undefined,
    keywords: undefined,
    description: undefined,
    icp: undefined,
    beian: undefined,
    storagePath: undefined,
    storage: 'local'
  });
  const query = () => {
    const params = {
      field: 'site'
    };
    getConfig(params).then((res) => {
      let data = JSON.parse(res.data);
      assignObject(form, data);

      if (icon.value == '' && data.icon != undefined) {
        icon.value.push(...icon.value, { url: data.icon });
      }
      if (logo.value == '' && data.logo != undefined) {
        logo.value.push(...logo.value, { url: data.logo });
      }
    });
  };
  const onBeforeUpload: BeforeUploadType = (file: File) => {
    if (!file.type.startsWith('image')) {
      message.error('只能选择图片');
      return false;
    }
    if (file.size / 1024 / 1024 > 2) {
      message.error('大小不能超过 2MB');
      return false;
    }
  };
  //上传图片
  const iconUpload = (d: ItemType) => {
    const item = icon.value.find((t) => t.uid === d.uid) ?? d;
    // item 包含的字段参考前面说明
    item.status = 'uploading';
    const formData = new FormData();
    formData.append('file', item.file);
    request({
      url: '/file/upload',
      method: 'post',
      data: formData,
      onUploadProgress: (e: any) => {
        // 文件上传进度回调
        if (e.lengthComputable) {
          item.progress = (e.loaded / e.total) * 100;
        }
      }
    })
      .then((res) => {
        if (res.data.code === 0) {
          item.status = 'done';
          item.url = res.data.data;
          form.icon = res.data.data;
        }
      })
      .catch((e: Error) => {
        message.warning(e.message);
        item.status = 'exception';
      });
  };
  const logoUpload = (d: ItemType) => {
    const item = logo.value.find((t) => t.uid === d.uid) ?? d;
    // item 包含的字段参考前面说明
    item.status = 'uploading';
    const formData = new FormData();
    formData.append('file', item.file);
    request({
      url: '/file/upload',
      method: 'post',
      data: formData,
      onUploadProgress: (e: any) => {
        // 文件上传进度回调
        if (e.lengthComputable) {
          item.progress = (e.loaded / e.total) * 100;
        }
      }
    })
      .then((res) => {
        if (res.data.code === 0) {
          item.status = 'done';
          item.url = res.data.data;
          form.logo = res.data.data;
        }
      })
      .catch((e: Error) => {
        message.warning(e.message);
        item.status = 'exception';
      });
  };
  const iconRemoveHandler = (item) => {
    icon.value.forEach((d: any) => {
      if (d.uid === item.uid) {
        icon.value = [];
        form.icon = '';
        d.deleted = 1;
      }
    });
  };
  const logoRemoveHandler = (item) => {
    logo.value.forEach((d: any) => {
      if (d.uid === item.uid) {
        logo.value = [];
        form.logo = '';
        d.deleted = 1;
      }
    });
  };
  /* 提交 */
  const submit = () => {
    if (!formRef.value) {
      return;
    }
    const newForm = {
      ...form,
      field: 'site'
    };
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        submitForm(newForm).then((res: any) => {
          if (res.code === 0) {
            loading.value = false;
            resetFields();
            query();
            return message.success(res.message);
          } else {
            loading.value = false;
            return message.error(res.message);
          }
        });
      })
      .catch(() => {});
  };
  query();
</script>

<script lang="ts">
  export default {
    name: 'FormBasic'
  };
</script>
